package com.atguigu.gmall.list.listener;

import com.atguigu.gmall.common.constans.MqConst;
import com.atguigu.gmall.list.service.ListService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
public class ListListener {
    @Autowired
    private ListService listService;

    //上架 添加ES
    //创建队列 BangDing 交换机
    @RabbitListener(bindings =@QueueBinding(
            value = @Queue(name = MqConst.QUEUE_GOODS_UPPER,durable = "true",autoDelete = "false"),
            exchange =@Exchange(name = MqConst.EXCHANGE_DIRECT_GOODS),
            key = {MqConst.ROUTING_GOODS_UPPER}))
    public void onSale(Message message , Channel channel , Long skuId){
        System.out.println("接收到的消息是："+skuId);
        //上架 添加ES
        listService.onSale(skuId);
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //下架 删除ES
    @RabbitListener(bindings =@QueueBinding(
            value =@Queue(name = MqConst.QUEUE_GOODS_LOWER,durable = "true",autoDelete = "false") ,
            exchange =@Exchange(name = MqConst.EXCHANGE_DIRECT_GOODS) ,
            key ={MqConst.ROUTING_GOODS_LOWER}
    ))
    public void cancelSale(Message message, Channel channel ,Long skuId){
        try {
            System.out.println("删除接收到的消息："+skuId);
            listService.cancelSale(skuId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
